﻿using CommonlyUtils;
using ImModels.Service.Models.Data;
using ImModels.View;
using ImModels.View.MsgJson;

namespace ImClientApi.Utils
{
    /// <summary>
    /// Im逻辑处理 主要是 发消息相关
    /// </summary>
    public class ImMsgLogic
    {
        /// <summary>
        /// 发送会话消息
        /// </summary>
        /// <param name="chat"></param>
        /// <param name="toBizUserIds"></param>
        /// <param name="senderUserKid"></param>
        /// <returns></returns>
        public static async Task SendSessionMsg(Msg_Session chat, IEnumerable<string> toBizUserIds, long senderUserKid)
        {
            if (toBizUserIds == null || toBizUserIds.Count() == 0) return;

            //3转换ID 转换得到 wsid 发送消息
            var allUsers = await DbUtils.DbHelper.GetListAsync<Users>(p => toBizUserIds.Contains(p.BizUserId) && p.IsDeleted == 0);

            if (allUsers.Count() == 0) return;
            var allUsersIds = allUsers.Select(p => p.KID).ToList();

            //获取在线客户端 发送socket消息
            var allWsOnline = ImHelper.GetClientListByOnline();
            var needToWsUserId = allUsersIds.Intersect(allWsOnline).ToList();
            if (needToWsUserId.Count() == 0) return;
            ImHelper.SendMessage(senderUserKid, needToWsUserId, chat);
        }


        /// <summary>
        /// 发送会话消息
        /// </summary>
        /// <param name="chat"></param>
        /// <param name="toBizUserIds"></param>
        /// <param name="senderUserKid"></param>
        /// <returns></returns>
        public static async Task SendReadMsg(Msg_Read chat, IEnumerable<string> toBizUserIds, long senderUserKid)
        {
            if (toBizUserIds == null || toBizUserIds.Count() == 0) return;

            //3转换ID 转换得到 wsid 发送消息
            var allUsers = await DbUtils.DbHelper.GetListAsync<Users>(p => toBizUserIds.Contains(p.BizUserId) && p.IsDeleted == 0);

            if (allUsers.Count() == 0) return;
            var allUsersIds = allUsers.Select(p => p.KID).ToList();

            //获取在线客户端 发送socket消息
            var allWsOnline = ImHelper.GetClientListByOnline();
            var needToWsUserId = allUsersIds.Intersect(allWsOnline).ToList();
            if (needToWsUserId.Count() == 0) return;
            ImHelper.SendMessage(senderUserKid, needToWsUserId, chat);
        }
        /// <summary>
        /// 发送消息
        /// 1.写 msg 表数据
        /// 2.筛选在线客户 发送 ws 消息
        /// </summary>
        /// <param name="enterId">企业唯一ID</param>
        /// <param name="chat">消息模型</param>
        /// <param name="toBizUserIds">接收者的业务Ids</param>
        /// <param name="senderUserKid">发送者的客户端id 对应的 User 表里面的 Kid,当 后一个参数 sendUsers有值值时 可为0</param>
        /// <param name="sendUsers">冗余发送者信息 有值 减少一次查询,有值的话</param>
        /// <returns></returns>
        public static async Task SendChatMsg(long enterId, Msg_Chat chat, IEnumerable<string> toBizUserIds, long senderUserKid, Users sendUsers = null)
        {
            /*
             * 1.根据发送至ID查询得到 发送者
             * 2.添加数据 到 Msg 表得到 msgid 无论是否在线 都写，不在线的当历史消息处理
             * 3.修改 chat 对象 构造发送消息json
             * 4.根据业务ID查询所有的需要发送的ws对象
             * 5.发送消息
             */
            //添加数据到 msg表 得到 msgid

            if (toBizUserIds == null || toBizUserIds.Count() == 0) return;

            //1 发送者
            if (sendUsers == null)
            {
                sendUsers = await DbUtils.DbHelper.GetOneAsync<Users>(p => p.KID == senderUserKid && p.EnterpriseId == enterId);
            }
            if (sendUsers == null) return;
            senderUserKid = sendUsers.KID;

            chat.send.name = chat.send.name ?? sendUsers.FullName;
            chat.send.nick = chat.send.nick ?? sendUsers.NickName;
            chat.send.img = chat.send.img ?? sendUsers.HeadImg;
            chat.send.uid = chat.send.uid ?? sendUsers.BizUserId;

            //2 写Msg表 如果 msgid大于0 则不写msg消息
            if (chat.send.msgid == 0)
            {
                #region 写一条消息到 Msgs 表
                var mySessionDb = await DbUtils.DbHelper.GetOneAsync<MySession>(p => p.SessionId == chat.sessionid && p.BizUserId == sendUsers.BizUserId && p.EnterpriseId == enterId);
                var msgId = Builder.GetNewSnowId();
                chat.send.msgid = msgId;

                var toBizUserId = mySessionDb.IsGroup == 0 ? mySessionDb.ToUserId : "";
                var toGroupId = Convert.ToInt64(mySessionDb.IsGroup == 1 ? mySessionDb.ToUserId : "0");
                var dayNum = Convert.ToInt32(DateTime.Now.ToString("yyyyMM"));
                var addDb = await DbUtils.DbHelper.AddItemAsync<Msgs>(new Msgs()
                {
                    KID = msgId,
                    States = 0,
                    CreateTime = DateTime.Now,
                    SessionId = chat.sessionid,
                    FromBizUserId = sendUsers.BizUserId,
                    ToBizUserId = toBizUserId,
                    ToGroupId = toGroupId,
                    MsgType = chat.send.stype,
                    Content = chat.send.content.ToJson(),
                    ReadTime = "",
                    DayNum = dayNum
                });
                #endregion
            }

            //3转换ID 转换得到 wsid 发送消息
            var allUsers = await DbUtils.DbHelper.GetListAsync<Users>(p => toBizUserIds.Contains(p.BizUserId) && p.EnterpriseId == enterId && p.IsDeleted == 0);

            if (allUsers.Count() == 0) return;
            var allUsersIds = allUsers.Select(p => p.KID).ToList();

            //获取在线客户端 发送socket消息
            var allWsOnline = ImHelper.GetClientListByOnline();
            var needToWsUserId = allUsersIds.Intersect(allWsOnline).ToList();
            if (needToWsUserId.Count() == 0) return;
            ImHelper.SendMessage(senderUserKid, needToWsUserId, chat);
        }

    }
}
